package cn.com.sise.controller;

import cn.com.sise.pojo.*;
import cn.com.sise.service.*;
import cn.com.sise.utils.DelFile;
import cn.com.sise.utils.FileUploadUtils;
import cn.com.sise.utils.Page;
import cn.com.sise.utils.VideoUpdateUtils;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Controller
@RequestMapping("/admin")
public class AdminController {
    private AdminService adminService;
    private UserService userService;
    private DictionaryService dictionaryService;
    private FeedbackService feedbackService;
    private AssistanceService assistanceService;
    private ResourcesService resourcesService;
    private ExerciseService exerciseService;

    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setDictionaryService(DictionaryService dictionaryService) {
        this.dictionaryService = dictionaryService;
    }

    @Autowired
    public void setFeedbackService(FeedbackService feedbackService) {
        this.feedbackService = feedbackService;
    }

    @Autowired
    public void setAssistanceService(AssistanceService assistanceService) {
        this.assistanceService = assistanceService;
    }

    @Autowired
    public void setResourcesService(ResourcesService resourcesService) {
        this.resourcesService = resourcesService;
    }

    @Autowired
    public void setExerciseService(ExerciseService exerciseService) {
        this.exerciseService = exerciseService;
    }

    /**
     * 管理员登录
     *
     * @param name     用户名
     * @param password 密码
     * @param code     验证码
     * @param model    跳转页面
     * @param session  session
     * @return 跳转视图
     */
    @RequestMapping("/adminLogin")
    public String login(String name, String password, String code, Model model, HttpSession session) {
        System.err.println("========================================" +
                "管理员正在登录(用户名:" + name + ",密码:" + password + ")========================================");
        if (!name.equals("") && !password.equals("")) {
            //获取验证码
            String codeStr = (String) session.getAttribute("verifyCode");
            //查询用户
            Admin admin = adminService.login(name, password);
            if (code.equalsIgnoreCase(codeStr)) {
                if (admin != null) {
                    //将用户信息存入session
                    session.setAttribute("adminInfo", admin);
                    System.err.println("========================================" +
                            "管理员登录成功========================================");
                    return "/admin/index";
                } else {
                    model.addAttribute("name", name);
                    model.addAttribute("password", password);
                    model.addAttribute("msg", "输入的账号或密码错误，请重新输入！");
                    return "/admin/login";
                }
            } else {
                model.addAttribute("name", name);
                model.addAttribute("password", password);
                model.addAttribute("msg", "验证码错误！");
                return "/admin/login";
            }
        } else {
            model.addAttribute("msg", "输入的账号密码为空值！");
            return "/jsp/error";
        }
    }

    /**
     * 加载index时候同时加载欢迎页
     *
     * @param model 视图
     * @return 跳转视图
     */
    @RequestMapping("/toWelcome")
    public String toWelcome(Model model) {
        System.err.println("========================================" +
                "管理员正在加载欢迎页========================================");
        int userTotal = userService.getTotal();
        int dictionaryTotal = dictionaryService.getDictionaryTotal();
        int feedBackTotal = feedbackService.getFeedbackTotal();
        //最新的五条反馈
        List<User> userList = feedbackService.selectFeedbackLimit(5);
        model.addAttribute("userTotal", userTotal);
        model.addAttribute("dictionaryTotal", dictionaryTotal);
        model.addAttribute("feedBackTotal", feedBackTotal);
        model.addAttribute("newFeedBack", userList);
        return "/admin/welcome";
    }

    /**
     * 管理员退出登录
     *
     * @param session session
     * @return 跳转视图
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        System.err.println("========================================" +
                "管理员退出========================================");
        //清除session
        session.invalidate();
        //重定向到登录页面
        return "/admin/login";
    }

    /**
     * 进入用户管理页面
     *
     * @param request   请求参数
     * @param modelView 视图
     * @return 跳转视图
     */
    @RequestMapping("/userList")
    public ModelAndView toUserList(HttpServletRequest request, ModelAndView modelView) {
        System.err.println("========================================" +
                "管理员正在访问用户管理界面========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 10;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<User> userList = userService.getList(page.getStart(), page.getCount());

        //获取用户总数
        int total = userService.getTotal();
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelView.addObject("page", page);
        modelView.addObject("userList", userList);
        //利用setViewName设定跳转页面
        modelView.setViewName("/admin/userList");

        return modelView;
    }

    /**
     * 管理员添加用户
     *
     * @param user  添加用户信息
     * @param model 视图
     * @return 跳转视图
     */
    @RequestMapping("/addUser")
    public String addUser(User user, Model model) {
        System.err.println("========================================" +
                "管理员正在添加用户界面========================================");
        if (userService.getUserByName(user.getName()) == null) {
            if (userService.insertUser(user) > 0) {
                model.addAttribute("msg", "添加用户成功！");
                System.err.println("========================================" +
                        "管理员添加了" + user.getName() + "用户名的用户========================================");
                return "redirect:/admin/userList.do";
            } else {
                model.addAttribute("msg", "添加用户失败！");
            }
        } else {
            model.addAttribute("msg", "该用户已存在！");
            model.addAttribute("userBack", user);
        }
        return "/admin/addUser";
    }

    /**
     * 管理员模糊用户查询
     *
     * @param nameLike  输入的模糊用户名
     * @param request   请求参数
     * @param modelView 视图
     * @return 视图
     */
    @RequestMapping("/getUserLike")
    public ModelAndView getUserLike(@RequestParam(value = "nameLike") String nameLike, HttpServletRequest request, ModelAndView modelView) {
        System.err.println("========================================" +
                "管理员正在使用用户模糊查询输入值为:[" + nameLike + "]========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 5;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<User> userList = userService.getListLike(nameLike, page.getStart(), page.getCount());

        //获取查询用户总数
        int total = userService.getLikeTotal(nameLike);
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelView.addObject("page", page);
        modelView.addObject("userList", userList);
        modelView.addObject("nameLike", nameLike);
        //利用setViewName设定跳转页面
        modelView.setViewName("/admin/userListLike");

        return modelView;
    }

    /**
     * 重定向到用户列表
     *
     * @return 跳转视图
     */
    @RequestMapping("/toUserList")
    public String toUserList() {
        return "redirect:/admin/userList.do";
    }

    /**
     * 管理员批量删除用户
     *
     * @param ids 传入的用户id
     * @return 视图跳转
     */
    @RequestMapping("/deleteUsers")
    public String deleteUsers(int[] ids) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + Arrays.toString(ids) + "]的用户信息========================================");
        for (int id : ids) {
            User user = new User();
            user.setUserId(id);
            //删除学生
            userService.deleteUser(user);
        }
        return "redirect:/admin/userList.do";
    }

    /**
     * 管理员删除单个用户
     *
     * @param user_id 用户ID
     * @return 跳转视图
     */
    @RequestMapping("/deleteUserById")
    public String deleteUserById(@RequestParam int user_id) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + user_id + "]的用户========================================");
        User user = new User();
        user.setUserId(user_id);
        userService.deleteUser(user);
        return "redirect:/admin/userList.do";
    }

    /**
     * 跳转至用户修改页面
     *
     * @param user_id 用户ID
     * @param model   视图
     * @return 跳转视图
     */
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(@RequestParam int user_id, Model model) {
        System.err.println("========================================" +
                "管理员正在修改ID为:[" + user_id + "]的用户信息========================================");
        User u = new User();
        u.setUserId(user_id);
        User user = userService.selectUserById(u);
        model.addAttribute("user", user);
        return "/admin/updateUser";
    }

    /**
     * 管理员提交修改用户
     *
     * @param user  修改用户信息
     * @param model 视图
     * @return 跳转视图
     */
    @RequestMapping("/updateUser")
    public String updateUser(User user, Model model) {
        System.err.println("========================================" +
                "管理员提交了修改[" + user.getName() + "]的用户信息========================================");
        User user1 = userService.getUserByName(user.getName());
        if (user1 != null) {
            if (user1.getUserId() == user.getUserId()) {
                if (userService.updateUser(user) == 1) {
                    return "redirect:/admin/userList.do";
                } else {
                    model.addAttribute("msg", "修改失败！");
                    return "/admin/updateUser";
                }
            }
            model.addAttribute("msg", "该用户被注册！");
            return "/admin/updateUser";
        } else {
            if (userService.updateUser(user) == 1) {
                return "redirect:/admin/userList.do";
            } else {
                model.addAttribute("msg", "修改失败！");
                return "/admin/updateUser";
            }
        }
    }

    /**
     * 欢迎页获取前七天的用户注册数和反馈数
     *
     * @param numberStr 前端传入的前七天日期
     * @return 跳转视图
     */
    @RequestMapping("/getCountForTime")
    public @ResponseBody
    List<String> getUserCountForTime(@RequestBody String numberStr) {
        System.err.println("========================================" +
                "管理员正在获取前七天的用户注册数和反馈数========================================");
        List<String> numbers = JSON.parseArray(numberStr, String.class);
        List<String> resultList = new ArrayList<String>();
        for (int i = 0; i < 7; i++) {
            resultList.add(String.valueOf(userService.getTimeForUser(numbers.get(i))));
        }
        for (int i = 0; i < 7; i++) {
            resultList.add(String.valueOf(feedbackService.getTimeForFeedback(numbers.get(i))));
        }
        return resultList;
    }

    /**
     * 跳转到词库管理
     *
     * @param request      请求参数
     * @param modelAndView 视图
     * @return 跳转视图
     */
    @RequestMapping("/dictionaryList")
    public ModelAndView dictionaryList(HttpServletRequest request, ModelAndView modelAndView) {
        System.err.println("========================================" +
                "管理员正在访问词库管理界面========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 4;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<Dictionary> dictionaryList = dictionaryService.getDictionaryList(page.getStart(), page.getCount());

        //获取用户总数
        int total = dictionaryService.getDictionaryTotal();
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelAndView.addObject("page", page);
        modelAndView.addObject("dictionaryList", dictionaryList);
        //利用setViewName设定跳转页面
        modelAndView.setViewName("/admin/dictionaryList");
        return modelAndView;
    }

    /**
     * 重定向到单词列表
     *
     * @return 跳转视图
     */
    @RequestMapping("/toDictionaryList")
    public String toDictionaryList() {
        return "redirect:/admin/dictionaryList.do";
    }

    /**
     * 管理员添加单词
     *
     * @param dictionary 添加单词信息
     * @param model      视图
     * @return 跳转视图
     */
    @RequestMapping("/addDictionary")
    public String addDictionary(Dictionary dictionary, Model model) {
        System.err.println("========================================" +
                "管理员正在添加词库界面========================================");
        if (dictionaryService.selectDictionary(dictionary) == null) {
            if (dictionaryService.insertDictionary(dictionary) > 0) {
                model.addAttribute("msg", "添加单词成功！");
                System.err.println("========================================" +
                        "管理员添加了单词[" + dictionary.getWord() + "]========================================");
                return "redirect:/admin/dictionaryList.do";
            } else {
                model.addAttribute("msg", "添加单词失败！");
            }
        } else {
            model.addAttribute("msg", "该单词已存在！");
            model.addAttribute("dictionaryBack", dictionary);
        }
        return "/admin/addDictionary";
    }

    /**
     * 管理员批量删除单词
     *
     * @param ids 前端传入要删除的单词ID
     * @return 跳转视图
     */
    @RequestMapping("/deleteDictionaries")
    public String deleteDictionaries(int[] ids) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + Arrays.toString(ids) + "]的单词信息========================================");
        for (int id : ids) {
            Dictionary dictionary = new Dictionary();
            dictionary.setDictionaryId(id);
            //删除学生
            dictionaryService.deleteDictionary(dictionary);
        }
        return "redirect:/admin/dictionaryList.do";
    }

    /**
     * 管理员删除单个单词
     *
     * @param dictionary_id 传入的删除单词的ID
     * @return 跳转视图
     */
    @RequestMapping("/deleteDictionaryById")
    public String deleteDictionaryById(@RequestParam int dictionary_id) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + dictionary_id + "]的单词========================================");
        Dictionary dictionary = new Dictionary();
        dictionary.setDictionaryId(dictionary_id);
        dictionaryService.deleteDictionary(dictionary);
        return "redirect:/admin/dictionaryList.do";
    }

    /**
     * 管理员跳转至修改单词页面
     *
     * @param dictionary_id 修改单词的ID
     * @param model         视图
     * @return 跳转视图
     */
    @RequestMapping("/toUpdateDictionary")
    public String toUpdateDictionary(@RequestParam int dictionary_id, Model model) {
        System.err.println("========================================" +
                "管理员正在修改ID为:[" + dictionary_id + "]的单词信息========================================");
        Dictionary d = new Dictionary();
        d.setDictionaryId(dictionary_id);
        Dictionary dictionary = dictionaryService.selectDictionary(d);
        model.addAttribute("dictionary", dictionary);
        return "/admin/updateDictionary";
    }

    /**
     * 管理员修改单词提交
     *
     * @param dictionary 修改的单词的信息
     * @param model      视图
     * @return 跳转视图
     */
    @RequestMapping("/updateDictionary")
    public String updateDictionary(Dictionary dictionary, Model model) {
        System.err.println("========================================" +
                "管理员提交了修改[" + dictionary.getWord() + "]的单词信息========================================");
        Dictionary dic = new Dictionary();
        dic.setWord(dictionary.getWord());
        Dictionary dictionary1 = dictionaryService.selectDictionary(dic);
        if (dictionary1 != null) {
            if (dictionary1.getDictionaryId() == dictionary.getDictionaryId()) {
                if (dictionaryService.updateDictionary(dictionary) == 1) {
                    return "redirect:/admin/dictionaryList.do";
                } else {
                    model.addAttribute("msg", "修改失败!");
                    return "/admin/updateDictionary";
                }
            }
            model.addAttribute("msg", "该用户被注册！");
            return "/admin/updateDictionary";
        } else {
            if (dictionaryService.updateDictionary(dictionary) == 1) {
                return "redirect:/admin/dictionaryList.do";
            } else {
                model.addAttribute("msg", "修改失败!");
                return "/admin/updateDictionary";
            }
        }
    }

    /**
     * 管理员模糊单词查询
     *
     * @param wordLike  输入的模糊单词
     * @param request   请求参数
     * @param modelView 视图
     * @return 跳转视图
     */
    @RequestMapping("/getDictionaryLike")
    public ModelAndView getDictionaryLike(@RequestParam(value = "wordLike") String wordLike, HttpServletRequest request, ModelAndView modelView) {
        System.err.println("=======================================" +
                "管理员正在使用用户模糊查询输入值为:[" + wordLike + "]========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 4;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<Dictionary> dictionaryList = dictionaryService.getListLike(wordLike, page.getStart(), page.getCount());

        //获取查询用户总数
        int total = dictionaryService.getLikeTotal(wordLike);
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelView.addObject("page", page);
        modelView.addObject("dictionaryList", dictionaryList);
        modelView.addObject("wordLike", wordLike);
        //利用setViewName设定跳转页面
        modelView.setViewName("/admin/dictionaryListLike");
        return modelView;
    }

    /**
     * 管理员跳转至反馈管理
     *
     * @param request      请求参数
     * @param modelAndView 视图
     * @return 跳转视图
     */
    @RequestMapping("/toFeedback")
    public ModelAndView toFeedback(HttpServletRequest request, ModelAndView modelAndView) {
        System.err.println("========================================" +
                "管理员正在访问反馈管理界面========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 10;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<User> userList = userService.getList(page.getStart(), page.getCount());

        //获取用户总数
        int total = userService.getTotal();
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelAndView.addObject("page", page);
        modelAndView.addObject("userList", userList);
        //利用setViewName设定跳转页面
        modelAndView.setViewName("/admin/feedBackUserList");

        return modelAndView;
    }

    /**
     * 重定向至用户反馈的用户列表
     *
     * @return 跳转视图
     */
    @RequestMapping("/toFeedbackUserList")
    public String toFeedbackUserList() {
        return "redirect:/admin/toFeedback.do";
    }

    /**
     * 跳转ID为user_id的用户的反馈信息
     *
     * @param user_id      用户ID
     * @param modelAndView 视图
     * @param request      请求参数
     * @return 跳转视图
     */
    @RequestMapping("/toFeedbackDetail")
    public ModelAndView toFeedbackDetail(@RequestParam(value = "user_id") int user_id, ModelAndView modelAndView, HttpServletRequest request) {
        System.err.println("========================================" +
                "管理员正在访问用户[" + user_id + "]的反馈界面========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 5;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<Feedback> feedbackList = feedbackService.selectFeedbackByUserID(user_id, start, count);

        //获取该用户反馈总数
        int total = feedbackService.getTotalFeedbackByUserID(user_id);
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelAndView.addObject("page", page);
        modelAndView.addObject("feedbackList", feedbackList);
        modelAndView.addObject("userId",user_id);
        //利用setViewName设定跳转页面
        modelAndView.setViewName("/admin/feedBackDetail");
        return modelAndView;
    }

    /**
     * 反馈中的用户模糊查询
     *
     * @param nameLike  输入的模糊字段
     * @param request   请求参数
     * @param modelView 视图
     * @return 跳转视图
     */
    @RequestMapping("/getFeedbackUser")
    public ModelAndView getFeedbackUser(@RequestParam(value = "nameLike") String nameLike, HttpServletRequest request, ModelAndView modelView) {
        System.err.println("========================================" +
                "管理员正在使用反馈中的用户模糊查询输入值为:[" + nameLike + "]========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 10;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<User> userList = userService.getListLike(nameLike, page.getStart(), page.getCount());

        //获取查询用户总数
        int total = userService.getLikeTotal(nameLike);
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelView.addObject("page", page);
        modelView.addObject("userList", userList);
        modelView.addObject("nameLike", nameLike);
        //利用setViewName设定跳转页面
        modelView.setViewName("/admin/feedBackUserListLike");

        return modelView;
    }

    /**
     * 根据反馈ID删除反馈
     *
     * @param feedback_id 反馈的ID
     * @param user_id     用户的ID
     * @return 重定向
     */
    @RequestMapping("/deleteFeedbackById")
    public String deleteFeedbackById(@RequestParam(value = "feedback_id") int feedback_id, @RequestParam(value = "user_id") int user_id) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + feedback_id + "]的反馈========================================");
        Feedback feedback = new Feedback();
        feedback.setFeedbackId(feedback_id);
        feedbackService.deleteFeedback(feedback);
        return "redirect:/admin/toFeedbackDetail.do?user_id=" + user_id;
    }

    /**
     * 用户进入反馈解决页面
     *
     * @param feedback_id 反馈的ID
     * @param model       视图
     * @return 跳转视图
     */
    @RequestMapping("/toSolutionFeedback")
    public String toSolutionFeedback(@RequestParam(value = "feedback_id") int feedback_id, Model model) {
        System.err.println("========================================" +
                "管理员正在解决ID为:[" + feedback_id + "]的反馈========================================");
        Feedback feedback = feedbackService.selectFeedbackByFeedId(feedback_id);
        model.addAttribute("feedback", feedback);
        return "/admin/solutionFeedback";
    }

    /**
     * 管理员提交反馈解决方案
     *
     * @param user_id  用户ID
     * @param feedback 提交的反馈信息
     * @param model    视图
     * @return 跳转视图
     */
    @RequestMapping("/solutionFeedbackSubmit")
    public String solutionFeedbackSubmit(@RequestParam(value = "user_id") int user_id, Feedback feedback, Model model) {
        if (feedbackService.updateFeedback(feedback) == 1) {
            System.err.println("========================================" +
                    "管理员提交了用户ID为:[" + user_id + "]的反馈========================================");
            return "redirect:/admin/toFeedbackDetail.do?user_id=" + user_id;
        } else {
            model.addAttribute("msg", "提交反馈失败！");
            return "/admin/feedBackDetail";
        }
    }

    /**
     * 跳转至用户帮助页面
     *
     * @param modelView 视图
     * @param request   请求参数
     * @return 跳转视图
     */
    @RequestMapping("/toUserHelp")
    public ModelAndView toUserHelp(ModelAndView modelView, HttpServletRequest request) {
        System.err.println("========================================" +
                "管理员正在访问用户帮助界面========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 5;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<Assistance> assistanceList = assistanceService.getClassificationDis(start, count);

        //获取分类总数
        int total = assistanceService.getClassificationDisTotal();
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelView.addObject("page", page);
        modelView.addObject("assistanceList", assistanceList);
        //利用setViewName设定跳转页面
        modelView.setViewName("/admin/assistanceList");
        return modelView;
    }

    /**
     * 删除某个分类的帮助信息
     *
     * @param classification 帮助分类
     * @return 跳转视图
     */
    @RequestMapping("/deleteForClass")
    public String deleteForClass(@RequestParam(value = "classification") String classification) {
        System.err.println("========================================" +
                "管理员正在删除[" + classification + "]分类的用户帮助========================================");
        Assistance assistance = new Assistance();
        assistance.setClassification(classification);
        assistanceService.deleteForClass(assistance);
        System.err.println("========================================" +
                "管理员删除[" + classification + "]分类的用户帮助成功！========================================");
        return "redirect:/admin/toUserHelp.do";
    }

    /**
     * 添加用户帮助信息
     *
     * @param assistance 传入的帮助信息
     * @param model      视图
     * @return 跳转视图
     */
    @RequestMapping("/addAssistance")
    public String addAssistance(Assistance assistance, Model model) {
        System.err.println("========================================" +
                "管理员正在添加[" + assistance.getSituation() + "]的用户帮助========================================");
        if (assistanceService.insertAssistance(assistance) > 0) {
            System.err.println("========================================" +
                    "管理员正在添加[" + assistance.getSituation() + "]的用户帮助成功！========================================");
            return "redirect:/admin/toUserHelp.do";
        } else {
            model.addAttribute("msg", "添加失败！");
            System.err.println("========================================" +
                    "管理员正在添加[" + assistance.getSituation() + "]的用户帮助失败！========================================");
            return "/admin/addAssistance";
        }
    }

    /**
     * 跳转至分类帮助页面
     *
     * @param classification 帮助分类
     * @param model          视图
     * @return 跳转视图
     */
    @RequestMapping("/toAssistanceDetail")
    public String toAssistanceDetail(@RequestParam(value = "classification") String classification, Model model) {
        System.err.println("========================================" +
                "管理员正在分类[" + classification + "]的页面========================================");
        Assistance ass = new Assistance();
        ass.setClassification(classification);
        List<Assistance> assistanceList = assistanceService.selectAssistance(ass);
        model.addAttribute("classification", classification);
        model.addAttribute("assistanceList", assistanceList);
        return "/admin/assistanceDetail";
    }

    /**
     * 管理员批量删除帮助
     *
     * @param ids            选中的ID
     * @param classification 传入的分类参数（用于重定向到自身页面）
     * @param attr           拼接url防止中文乱码
     * @return 跳转视图
     */
    @RequestMapping("/deleteAssistants")
    public String deleteAssistants(int[] ids, @RequestParam(value = "classification") String classification, RedirectAttributes attr) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + Arrays.toString(ids) + "]的帮助信息========================================");
        for (int id : ids) {
            Assistance as = new Assistance();
            as.setHelpId(id);
            assistanceService.deleteByHelpId(as);
        }
        attr.addAttribute("classification", classification);
        return "redirect:/admin/toAssistanceDetail.do";
    }

    /**
     * 管理员删除单个帮助
     *
     * @param helpId         传入的帮助ID
     * @param classification 传入的分类参数（用于重定向到自身页面）
     * @param attr           拼接url防止中文乱码
     * @return 跳转视图
     */
    @RequestMapping("/deleteAssistantsOne")
    public String deleteAssistantsOne(@RequestParam(value = "helpId") int helpId, @RequestParam(value = "classification") String classification, RedirectAttributes attr) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + helpId + "]的帮助========================================");
        Assistance ass = new Assistance();
        ass.setHelpId(helpId);
        assistanceService.deleteByHelpId(ass);
        attr.addAttribute("classification", classification);
        return "redirect:/admin/toAssistanceDetail.do";
    }

    /**
     * 跳转至帮助更新页面
     *
     * @param helpId         帮助ID
     * @param classification 传入的帮助分类
     * @param model          视图
     * @return 跳转视图
     */
    @RequestMapping("/toUpdateAssistance")
    public String toUpdateAssistance(@RequestParam(value = "helpId") int helpId, @RequestParam(value = "classification") String classification, Model model) {
        System.err.println("========================================" +
                "管理员更新了分类为:[" + classification + "],ID为:[" + helpId + "]的帮助========================================");
        Assistance assistance = assistanceService.getAssistanceById(helpId);
        model.addAttribute("assistance", assistance);
        model.addAttribute("classification", classification);
        return "/admin/updateAssistance";
    }

    /**
     * 更新帮助提交
     *
     * @param classification 帮助的分类
     * @param assistance     提交的修改信息
     * @param attr           拼接url防止中文乱码
     * @param model          视图
     * @return 跳转视图
     */
    @RequestMapping("/updateAssistanceSubmit")
    public String updateAssistanceSubmit(@RequestParam(value = "c") String classification, Assistance assistance, RedirectAttributes attr, Model model) {
        System.err.println("========================================" +
                "管理员正在更新分类为:[" + classification + "]的帮助========================================");
        if (assistanceService.updateAssistance(assistance) > 0) {
            attr.addAttribute("classification", classification);
            System.err.println("========================================" +
                    "管理员更新了分类为:[" + classification + "]的帮助成功========================================");
            return "redirect:/admin/toAssistanceDetail.do";
        } else {
            System.err.println("========================================" +
                    "管理员更新了分类为:[" + classification + "]的帮助失败========================================");
            model.addAttribute("msg", "修改失败！");
            model.addAttribute("assistance", assistance);
            return "/admin/updateAssistance";
        }
    }

    /**
     * 跳转至视听资源页面
     *
     * @param request      请求参数
     * @param modelAndView 视图
     * @return 跳转视图
     */
    @RequestMapping("/toResourceList")
    public ModelAndView toResourceList(HttpServletRequest request, ModelAndView modelAndView) {
        System.err.println("========================================" +
                "管理员正在访问词库管理界面========================================");
        int start = 0;//初始化开始数据的索引 也就是所在页面的第一行 如第一页第一行是第0条，第二页第一行是第6条 以此类推
        int count = 4;//每页显示的条目数
        try {
            start = Integer.parseInt(request.getParameter("page.start"));
            count = Integer.parseInt(request.getParameter("page.count"));
        } catch (Exception ignored) {
        }
        Page page = new Page(start, count);
        //每次从数据库中取出部分数据，可防止内存溢出
        List<Resources> resourcesList = resourcesService.selectResourcesPage(page.getStart(), page.getCount());

        //获取视听总数
        int total = resourcesService.getResourcesTotal();
        page.setTotal(total);//设置page对象的总数据量

        //通过addObject存储page和用户list
        modelAndView.addObject("page", page);
        modelAndView.addObject("resourcesList", resourcesList);
        //利用setViewName设定跳转页面
        modelAndView.setViewName("/admin/resourcesList");
        return modelAndView;
    }

    /**
     * 添加视听资源
     *
     * @param attach    上传的文件
     * @param resources 传入的文件数据
     * @param request   请求参数
     * @param model     视图
     * @return 跳转视图
     * @throws IOException 异常
     */
    @RequestMapping("/addResource")
    public String addResource(@RequestParam(value = "video", required = false) MultipartFile attach, Resources resources, HttpServletRequest request, Model model) throws IOException {
        System.err.println("========================================" +
                "管理员正在添加视听资源========================================");
        String sqlPath, realPath;
        if (resourcesService.selectResourcesByRCode(resources.getRCode())) {
            if (!attach.isEmpty()) {
                FileUploadUtils utils = new FileUploadUtils(attach, request);
                if (VideoUpdateUtils.checkVideoFile(utils.getOriginalFilename())) {
                    //创建目录
                    File filePath = new File(utils.getDirPath("video"));
                    // 如果保存文件的地址不存在，就先创建目录
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    //上传文件
                    realPath = utils.getDirPathFileName("video", resources.getRCode());
                    attach.transferTo(new File(realPath));
                    sqlPath = utils.getSqlPathFileName("video", resources.getRCode());

                    resources.setUrl(sqlPath);
                    resources.setRealPath(realPath);
                    if (resourcesService.insertResource(resources) > 0) {
                        System.err.println("========================================" +
                                "管理员添加了标识码为:[" + resources.getRCode() + "]的视听资源========================================");
                        return "redirect:/admin/toResourceList.do";
                    } else {
                        model.addAttribute("msg", "上传失败！");
                        return "/admin/addResources";
                    }

                } else {
                    model.addAttribute("msg", "上传的文件类型不符合！");
                    return "/admin/addResources";
                }
            } else {
                model.addAttribute("msg", "上传的文件为空！");
                return "/admin/addResources";
            }
        } else {
            model.addAttribute("msg", "视听的唯一标识码已存在！");
            System.err.println("========================================" +
                    "标识码为:[" + resources.getRCode() + "]的视听资源已存在!========================================");
            return "/admin/addResources";
        }
    }

    /**
     * 跳转至修改视听页面
     *
     * @param resource_id 视听的ID
     * @param model       视图
     * @return 跳转视图
     */
    @RequestMapping("/toUpdateResource")
    public String toUpdateResource(@RequestParam(value = "resource_id") int resource_id, Model model) {
        Resources resources = resourcesService.selectResourcesById(resource_id);
        model.addAttribute("resources", resources);
        System.err.println("========================================" +
                "管理员正在前往修改视听资源========================================");
        return "/admin/updateResources";
    }

    /**
     * 更改视听资源
     *
     * @param attach    更新的视频文件
     * @param resources 传入的参数
     * @param request   请求参数
     * @param model     视图
     * @return 跳转视图
     * @throws IOException 异常
     */
    @RequestMapping("/updateResourceSubmit")
    public String updateResourceSubmit(@RequestParam(value = "video", required = false) MultipartFile attach, Resources resources, HttpServletRequest request, Model model) throws IOException {
        System.err.println("========================================" +
                "管理员正在修改标识码为:[" + resources.getRCode() + "]的视听资源========================================");
        String realPath, sqlPath;
        if (!attach.isEmpty()) {
            FileUploadUtils utils = new FileUploadUtils(attach, request);
            if (VideoUpdateUtils.checkVideoFile(utils.getOriginalFilename())) {
                //创建目录
                File filePath = new File(utils.getDirPath("video"));
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                //上传文件
                realPath = utils.getDirPathFileName("video", resources.getRCode());
                attach.transferTo(new File(realPath));
                sqlPath = utils.getSqlPathFileName("video", resources.getRCode());
                resources.setUrl(sqlPath);
                resources.setRealPath(realPath);
            } else {
                model.addAttribute("msg", "上传的文件类型不符合！");
                return "/admin/updateResources";
            }
        }

        if (resourcesService.updateResource(resources) > 0) {
            System.err.println("========================================" +
                    "管理员修改了标识码为:[" + resources.getRCode() + "]的视听资源========================================");
            return "redirect:/admin/toResourceList.do";
        } else {
            model.addAttribute("msg", "修改失败！");
            return "/admin/updateResources";
        }

    }

    /**
     * 管理员删除单个视听资源
     *
     * @param resource_id 视听ID
     * @return 重定向
     */
    @RequestMapping("/deleteResource")
    public String deleteResource(@RequestParam(value = "resource_id") int resource_id) {
        Resources resources = new Resources();
        resources.setResourceId(resource_id);
        //删除服务器的视频文件
        DelFile.delFile(resourcesService.selectResourcesById(resource_id).getRealPath());
        //删除数据库中的数据
        resourcesService.deleteResource(resources);
        System.err.println("========================================" +
                "管理员删除了ID为:[" + resource_id + "]的视听资源========================================");
        return "redirect:/admin/toResourceList.do";
    }

    /**
     * 管理员批量删除视听资源
     *
     * @param ids 传入的ID
     * @return 重定向
     */
    @RequestMapping("/deleteResources")
    public String deleteResources(int[] ids) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + Arrays.toString(ids) + "]的视听资源========================================");
        for (int id : ids) {
            Resources resources = new Resources();
            resources.setResourceId(id);
            DelFile.delFile(resourcesService.selectResourcesById(id).getRealPath());
            resourcesService.deleteResource(resources);
        }
        return "redirect:/admin/toResourceList.do";
    }

    /**
     * 管理员查看用户收藏资源
     *
     * @param user_id 用户ID
     * @param model   视图
     * @return 跳转视图
     */
    @RequestMapping("/getUserFavorite")
    public String getUserFavorite(@Param("user_id") int user_id, Model model) {
        System.err.println("========================================" +
                "管理员正在查看ID为:[" + user_id + "]的收藏========================================");
        List<User> dictionaryList = userService.getFavoritesDictionaryByUserId(user_id);
        List<User> resourcesList = userService.getFavoritesResourcesByUserId(user_id);
        model.addAttribute("dictionaryList", dictionaryList);
        model.addAttribute("resourcesList", resourcesList);
        return "/admin/showUserFavorite";
    }

    /**
     * 管理员查看用户历史资源
     *
     * @param user_id 用户ID
     * @param model   视图
     * @return 跳转视图
     */
    @RequestMapping("/getUserHistory")
    public String getUserHistory(@Param("user_id") int user_id, Model model) {
        System.err.println("========================================" +
                "管理员正在查看ID为:[" + user_id + "]的历史记录========================================");
        List<User> dictionaryList = userService.getHistoryDictionaryByUserId(user_id);
        List<User> resourcesList = userService.getHistoryResourcesByUserId(user_id);
        model.addAttribute("dictionaryList", dictionaryList);
        model.addAttribute("resourcesList", resourcesList);
        return "/admin/showUserHistory";
    }

    /**
     * 跳转至题库管理
     *
     * @param model 视图
     * @return 跳转视图
     */
    @RequestMapping("/toExerciseList")
    public String toExerciseList(Model model) {
        System.err.println("========================================" +
                "管理员正在跳转至题库管理========================================");
        List<Exercise> exerciseList = exerciseService.getAllExercises();
        model.addAttribute("exerciseList", exerciseList);
        return "/admin/exerciseList";
    }

    /**
     * 查看指定试卷ID的所有题目
     *
     * @param exercise_id 试卷ID
     * @param model       视图
     * @return 跳转视图
     */
    @RequestMapping("/toQuestionByExercise")
    public String toQuestionByExercise(@RequestParam(value = "exercise_id") int exercise_id, Model model) {
        System.err.println("========================================" +
                "管理员正在跳转至试卷ID为:[" + exercise_id + "]的所有题目========================================");
        List<Exercise> exerciseList = exerciseService.getAllQuestionById(exercise_id);
        model.addAttribute("exerciseList", exerciseList);
        model.addAttribute("exercise_id", exercise_id);
        return "/admin/questionList";
    }

    /**
     * 管理员添加试卷
     *
     * @param exercise 传入的试卷信息
     * @param model    视图
     * @return 跳转视图
     */
    @RequestMapping("/addExercise")
    public String addExercise(Exercise exercise, Model model) {
        if (exerciseService.insertExercise(exercise) > 0) {
            System.err.println("========================================" +
                    "管理员添加了试卷题目为:[" + exercise.getTitle() + "]的试卷成功========================================");
            return "redirect:/admin/toExerciseList.do";
        } else {
            System.err.println("========================================" +
                    "管理员添加了试卷题目为:[" + exercise.getTitle() + "]的试卷失败========================================");
            model.addAttribute("msg", "添加失败！");
            return "/admin/addExercise";
        }
    }

    /**
     * 管理员删除单个试卷
     *
     * @param exercise_id 传入的试卷ID
     * @return 跳转视图
     */
    @RequestMapping("/deleteExerciseOne")
    public String deleteExerciseOne(@RequestParam(value = "exercise_id") int exercise_id) {
        exerciseService.deleteExercise(exercise_id);
        System.err.println("========================================" +
                "管理员删除了试卷ID为:[" + exercise_id + "]的试卷========================================");
        return "redirect:/admin/toExerciseList.do";
    }

    /**
     * 管理员批量删除试卷
     *
     * @param ids 选中的试卷
     * @return 视图跳转
     */
    @RequestMapping("/deleteExerciseAll")
    public String deleteExerciseAll(int[] ids) {
        System.err.println("========================================" +
                "管理员删除了ID为:[" + Arrays.toString(ids) + "]的试卷========================================");
        for (int id : ids) {
            exerciseService.deleteExercise(id);
        }
        return "redirect:/admin/toExerciseList.do";
    }

    /**
     * 跳转至添加题目（携带试卷ID）
     *
     * @param exercise_id 试卷ID
     * @param model       视图
     * @return 跳转视图
     */
    @RequestMapping("/toAddQuestion")
    public String toAddQuestion(@RequestParam(value = "exercise_id") int exercise_id, Model model) {
        System.err.println("========================================" +
                "管理员跳转至试卷ID为:[" + exercise_id + "]中添加题目========================================");
        model.addAttribute("exercise_id", exercise_id);
        return "/admin/addQuestion";
    }

    /**
     * 添加题目提交
     *
     * @param e_id     携带的试卷ID
     * @param question 传入的题目信息
     * @param attr     重定向参数
     * @param model    视图
     * @return 跳转视图
     */
    @RequestMapping("/addQuestionSubmit")
    public String addQuestionSubmit(@RequestParam(value = "e_id") int e_id, Question question, RedirectAttributes attr, Model model) {
        question.setExerciseId(e_id);
        if (exerciseService.insertQuestion(question) > 0) {
            System.err.println("========================================" +
                    "管理员跳转至试卷ID为:[" + e_id + "]中添加题目成功========================================");
            attr.addAttribute("exercise_id", e_id);
            return "redirect:/admin/toQuestionByExercise.do";
        } else {
            model.addAttribute("msg", "添加失败!");
            return "/admin/addQuestion";
        }
    }

    /**
     * 删除单个试题
     *
     * @param question_id 试题的ID
     * @param e_id        试卷的ID
     * @param attr        重定向参数
     * @return 重定向
     */
    @RequestMapping("/deleteQuestionOne")
    public String deleteQuestionOne(@RequestParam(value = "question_id") int question_id, @RequestParam(value = "e_id") int e_id, RedirectAttributes attr) {
        Question question = new Question();
        question.setQuestionId(question_id);
        exerciseService.deleteQuestion(question);
        System.err.println("========================================" +
                "管理员删除了试卷ID为:[" + e_id + "],题目ID为:[" + question_id + "]的试题========================================");
        attr.addAttribute("exercise_id", e_id);
        return "redirect:/admin/toQuestionByExercise.do";
    }

    /**
     * 批量删除试题
     *
     * @param ids  选中的试题
     * @param e_id 试卷的ID
     * @param attr 重定向参数
     * @return 重定向
     */
    @RequestMapping("/deleteQuestionAll")
    public String deleteQuestionAll(int[] ids, @RequestParam(value = "e_id") int e_id, RedirectAttributes attr) {
        System.err.println("========================================" +
                "管理员删除了试卷ID为:[" + e_id + "],题目ID为:[" + Arrays.toString(ids) + "]的试题========================================");
        for (int id : ids) {
            Question question = new Question();
            question.setQuestionId(id);
            exerciseService.deleteQuestion(question);
        }
        attr.addAttribute("exercise_id", e_id);
        return "redirect:/admin/toQuestionByExercise.do";
    }

    /**
     * 跳转到修改试题页面（携带试卷ID）
     *
     * @param model       视图
     * @param exercise_id 试卷ID
     * @param question_id 试题ID
     * @return 跳转视图
     */
    @RequestMapping("/toUpdateQuestion")
    public String toUpdateQuestion(Model model, @RequestParam(value = "exercise_id") int exercise_id, @RequestParam(value = "question_id") int question_id) {
        System.err.println("========================================" +
                "管理员正在跳转到修改试题页面========================================");
        Question question = exerciseService.getQuestionById(question_id);
        model.addAttribute("question", question);
        model.addAttribute("exercise_id", exercise_id);
        return "/admin/updateQuestion";
    }

    /**
     * 修改试题提交
     *
     * @param e_id     试卷ID
     * @param question 提交修改试题的信息
     * @param attr     重定向参数
     * @param model    视图
     * @return 跳转视图
     */
    @RequestMapping("/updateQuestion")
    public String updateQuestion(@RequestParam(value = "e_id") int e_id, Question question, RedirectAttributes attr, Model model) {
        question.setExerciseId(e_id);
        if (exerciseService.updateQuestion(question) > 0) {
            attr.addAttribute("exercise_id", e_id);
            System.err.println("========================================" +
                    "管理员修改了试卷ID为:[" + e_id + "],题目ID为:[" + question.getQuestionId() + "]的试题成功========================================");
            return "redirect:/admin/toQuestionByExercise.do";
        } else {
            System.err.println("========================================" +
                    "管理员修改了试卷ID为:[" + e_id + "],题目ID为:[" + question.getQuestionId() + "]的试题失败========================================");
            model.addAttribute("msg", "修改失败！");
            return "/admin/updateQuestion";
        }
    }
}
